﻿Public Class frmFacture

    Public pNoDossier As Integer

    Private szSQL As String
    Private rs As ADODB.Recordset = Nothing
    Dim xRubrique As String = "FACTURE"
    Dim xSousRub As String = "FACTURE_LIG"
    Dim xOldNom As String
    Dim xOldCabinet As Integer
    Dim xNolig As Integer
    Dim xLastNoLig As Integer
    Dim xNbSousTotaux As Integer
    Dim dTotalTTC As Decimal
    Dim dTotalHT As Decimal

    Private Sub frmDevis_Activated(sender As Object, e As System.EventArgs) Handles Me.Activated

        If TabControl1.SelectedIndex = 0 Then
            TE_NOM.Focus()
        End If

    End Sub

    Private Sub frmFacture_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        Me.Text = xRubrique & " : " & pNoDossier.ToString
        Me.BackColor = getSocieteColor()
        ToolStripRubrique.Text = "FACTURE"
        InitComboCabinets(CB_CABINETS)
        InitComboQualite(CB_QUALITE)
        InitComboTVA(CB_TVA)
        InitComboTables(CB_MODEREG, "P_MODEREG")
        DossierToScreen()
        TabControl1.SelectedIndex = 0

    End Sub

    Private Sub BO_CREER_CLIENT_Click(sender As System.Object, e As System.EventArgs) Handles BO_CREER_CLIENT.Click

        ' Création d'un client
        frmClientMAJ.pCd_cli = 0
        frmClientMAJ.ShowDialog()

    End Sub

    Private Sub BO_WEB_Click(sender As System.Object, e As System.EventArgs) Handles BO_WEB.Click

        If Len(TE_WEBSITE.Text) > 0 Then
            ' Ouvrirr la page web du client
            Process.Start(TE_WEBSITE.Text)
        End If

    End Sub

    Private Sub BO_CLIENT_Click(sender As System.Object, e As System.EventArgs) Handles BO_CLIENT.Click

        ' consultation du client
        frmClientMAJ.pCd_cli = TE_CD_CLI.Text
        frmClientMAJ.ShowDialog()

    End Sub

    Private Sub BO_ENREGISTER_Click(sender As System.Object, e As System.EventArgs) Handles BO_ENREGISTER.Click

        If IsUserAuthorised(ctGestion) = False Then
            Exit Sub
        End If

        ScreenToDossier()
        Me.Close()

    End Sub

    Private Sub ScreenToDossier()

        If TE_CD_CLI.Text.Length = 0 Then
            MsgBox("Veuillez sélectionner un client !", MsgBoxStyle.Critical)
            Exit Sub
        End If

        ' maj la facture
        szSQL = "CALL spUPD_FACTURE('" & gSocieteCode & "'," & pNoDossier & "," & BO_DEVIS.Text & "," & BO_ORDRE.Text & "," & BO_DEM.Text & ",'" & _
             Format(TE_DATE.Value, "yyyy/MM/dd") & "'," & nz(TE_CD_CLI.Text) & ",'" & nq(TE_NOM.Text) & "','" & TE_TYPECLI.Text & "','" & _
             nq(TE_C_NOM.Text) & "','" & nq(TE_C_ADR.Text) & "','" & nq(TE_C_ADR2.Text) & "','" & TE_C_CP.Text & "','" & nq(TE_C_VILLE.Text) & "','" & _
             TE_C_TEL1.Text & "','" & TE_C_TEL2.Text & "','" & TE_C_TELP.Text & "','" & TE_C_FAX.Text & "','" & nq(TE_C_OBS.Text) & "','" & _
             TE_C_ETAGE.Text & "','" & TE_C_CODE.Text & "','" & TE_C_EMAIL.Text & "','" & CB_QUALITE.SelectedItem & "'," & getTailCodeFromCombo(CB_CABINETS.SelectedItem) & "," & _
             getTailCodeFromCombo(CB_EXPERTS.SelectedItem) & "," & getCodeFromCombo(CB_TVA.SelectedItem) & ",0,'" & nv(TE_NOSIN.Text) & "','" & _
             nv(TE_NOPOL.Text) & "','" & nv(TE_VREF.Text) & "','" & nv(TE_REF_EXPERT.Text) & "','" & nv(TE_LIBCOMPL.Text) & "','" & Mid(CB_TYPE_TRAV.SelectedItem, 1, 1) & "','" & _
             TE_GROUPE.Text & "'," & CInt(ChkA_REVOIR.Checked) & "," & CInt(TE_NOTARIF.Text) & ",'" & nq(TE_AL_ATTENTION.Text) & "','" & UCase(gUserCode) & "')"
        GetRecordset(ctDSN_DEVFAC, szSQL, rs)
        If rs.RecordCount > 0 Then
            pNoDossier = rs.Fields("newnumero").Value
        End If
        rs.Close()

    End Sub

    Private Sub DossierToScreen()

        ' Nouvelle Création ?
        If pNoDossier = 0 Then
            ' RAB des champs du form
            ClearTextBoxes(Me)
            xOldNom = ""      ' ancien nom client

            BO_ORDRE.Text = "0"
            BO_DEVIS.Text = "0"
            BO_DEM.Text = "0"
            TE_DATE.Value = Today
            TE_DATE_ECHEANCE.Value = DateAdd(DateInterval.Day, 8, TE_DATE.Value)

            CB_CABINETS.SelectedIndex = getTailCodePosition(CB_CABINETS, "1")
            xOldCabinet = 1
            ' remplir le combo experts selon le cabinet lu
            InitComboExperts(CB_EXPERTS, getTailCodeFromCombo(CB_CABINETS.SelectedItem))
            InitComboExperts(CB_EXPERTS, "1")
            CB_EXPERTS.SelectedIndex = getTailCodePosition(CB_EXPERTS, "1")
            CB_TVA.SelectedIndex = CB_TVA.FindString("4")
            CB_QUALITE.SelectedIndex = CB_QUALITE.FindString("MR")
            CB_TYPE_TRAV.SelectedIndex = CB_TYPE_TRAV.FindString("S")

            TE_NOM.Text = ""
            TE_CD_CLI.Text = ""
            ChkA_REVOIR.Checked = False
            ChkA_REVOIR.ForeColor = Color.Black
        Else
            'Lire le DOSSIER

            szSQL = "CALL spGET_ENTETE('" & gSocieteCode & "','" & xRubrique & "'," & pNoDossier & ")"
            GetRecordset(ctDSN_DEVFAC, szSQL, rs)
            If rs.RecordCount < 1 Then
                rs.Close()
                Exit Sub
            End If

            ' Afficher Entête document
            EntetetoScreen()
            rs.Close()

        End If

    End Sub

    Private Sub EntetetoScreen()

        Dim rsClient As ADODB.Recordset = Nothing

        ' ===== Lire le CLIENT et afficher le bloc CLIENT
        TE_CD_CLI.Text = Format(rs.Fields("cd_cli").Value, "000000")

        szSQL = "CALL spGET_CLIENTS('" & gSocieteCode & "'," & TE_CD_CLI.Text & ")"
        GetRecordset(ctDSN_DEVFAC, szSQL, rsClient)
        If rsClient.RecordCount > 0 Then
            TE_QUALITE.Text = nv(rsClient.Fields("qualite").Value)
            TE_NOM.Text = rsClient.Fields("nom").Value
            xOldNom = TE_NOM.Text     ' ancien nom client
            TE_ADR.Text = fAdresseClient(rsClient)
            TE_COMMENT.Text = nv(rsClient.Fields("comment").Value)
            TE_EMAIL.Text = nv(rsClient.Fields("EMAIL").Value)
            TE_TYPECLI.Text = nv(rsClient.Fields("Type").Value)
            TE_WEBSITE.Text = nv(rsClient.Fields("website").Value)
            TE_NOCOMPTE.Text = nv(rsClient.Fields("NOCOMPTE").Value)
            TE_NOTARIF.Text = rsClient.Fields("notarif").Value
            TE_GROUPE.Text = rs.Fields("groupe").Value
        End If

        ' ===== afficher le bloc : CHANTIER
        CB_QUALITE.SelectedIndex = CB_QUALITE.FindString(rs.Fields("C_QUALITE").Value)
        TE_C_NOM.Text = nv(rs.Fields("c_nom").Value)
        ' si nom chantier non rempli mettre le nom client
        If TE_C_NOM.Text = "" Then
            TE_C_NOM.Text = TE_NOM.Text
        End If
        TE_C_ADR.Text = nv(rs.Fields("c_adr").Value)
        TE_C_ADR2.Text = nv(rs.Fields("C_ADR2").Value)
        TE_C_CP.Text = nv(rs.Fields("C_CP").Value)
        TE_C_VILLE.Text = nv(rs.Fields("C_VILLE").Value)
        TE_C_TEL1.Text = nv(rs.Fields("c_tel1").Value)
        TE_C_TEL2.Text = nv(rs.Fields("c_tel2").Value)
        TE_C_TELP.Text = nv(rs.Fields("c_TELP").Value)
        TE_C_FAX.Text = nv(rs.Fields("C_FAX").Value)
        TE_C_ETAGE.Text = nv(rs.Fields("C_ETAGE").Value)
        TE_C_CODE.Text = nv(rs.Fields("c_code").Value)
        TE_C_OBS.Text = nv(rs.Fields("C_OBS").Value)
        TE_C_EMAIL.Text = nv(rs.Fields("c_EMAIL").Value)
        CB_TYPE_TRAV.SelectedIndex = CB_TYPE_TRAV.FindString(rs.Fields("typeTrav").Value)
        CB_TVA.SelectedIndex = CB_TVA.FindString(rs.Fields("codetva").Value)

        ' ===== afficher le bloc : ASSURANCE
        CB_CABINETS.SelectedIndex = getTailCodePosition(CB_CABINETS, rs.Fields("cabinet").Value)
        xOldCabinet = rs.Fields("cabinet").Value
        ' remplir le combo experts selon le cabinet lu
        InitComboExperts(CB_EXPERTS, getTailCodeFromCombo(CB_CABINETS.SelectedItem))
        CB_EXPERTS.SelectedIndex = getTailCodePosition(CB_EXPERTS, rs.Fields("expert").Value.ToString)
        TE_NOSIN.Text = nv(rs.Fields("noSin").Value)
        TE_NOPOL.Text = nv(rs.Fields("noPol").Value)
        TE_VREF.Text = nv(rs.Fields("VREF").Value)
        TE_REF_EXPERT.Text = nv(rs.Fields("REF_EXPERT").Value)
        TE_LIBCOMPL.Text = nv(rs.Fields("LIBCOMPL").Value)

        ' ===== afficher le bloc : DOSSIER
        ChkA_REVOIR.Checked = rs.Fields("A_REVOIR").Value
        If ChkA_REVOIR.Checked = True Then
            ChkA_REVOIR.ForeColor = Color.Red
        Else
            ChkA_REVOIR.ForeColor = Color.Black
        End If
        TE_DATE.Value = rs.Fields("Date").Value
        TE_TOTALHT.Text = FormatCurrency(rs.Fields("totalht").Value)
        TE_TOTALTTC.Text = FormatCurrency(rs.Fields("totalttc").Value)
        CB_MODEREG.SelectedIndex = CB_MODEREG.FindString(rs.Fields("modereg").Value.ToString)
        TE_DATE_ECHEANCE.Value = rs.Fields("echeance").Value
        TE_MTREGL.Text = FormatCurrency(rs.Fields("mtregl").Value)
        TE_DATEREG.Text = IfDate(rs.Fields("datereg").Value)
        BO_DEVIS.Text = Format(rs.Fields("nodevis").Value, "000000")
        BO_ORDRE.Text = Format(rs.Fields("noordre").Value, "000000")
        BO_DEM.Text = Format(rs.Fields("NO_DD").Value, "000000")
        ' Demande existe ?
        If CLng(BO_DEM.Text) > 0 Then
            BO_DEM.Enabled = True
        Else
            BO_DEM.Enabled = False
        End If
        ' Devis existe ?
        If CLng(BO_ORDRE.Text) > 0 Then
            BO_ORDRE.Enabled = True
        Else
            BO_ORDRE.Enabled = False
        End If
        ' Facture existe
        If CLng(BO_DEVIS.Text) > 0 Then
            BO_DEVIS.Enabled = True
        Else
            BO_DEVIS.Enabled = False
        End If
        TE_DATE_STAMP.Text = "Modifié le " & rs.Fields("DATEMAJ").Value & " par " & UCase(rs.Fields("USERMAJ").Value)

    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles TabControl1.SelectedIndexChanged

        Select Case TabControl1.SelectedIndex
            Case 0  ' tab Fiche

            Case 1  ' tab Détails
                ' enregistrer le dossier ?
                ScreenToDossier()
                Call InitLignes(0)

            Case 2  ' tab Opération
                ' enregistrer le dossier ?
                ScreenToDossier()
                TE_NEW_NO.Value = pNoDossier

        End Select

    End Sub

    Private Sub InitLignes(ByVal ix As Integer)

        Dim nb As Integer = 0
        Dim xTauxTVA As Decimal

        ' effacer la listview
        LV_LIGNES.Items.Clear()
        dTotalHT = 0

        szSQL = "CALL spGET_LIGNES('" & gSocieteCode & "','" & xSousRub & "'," & pNoDossier & ",0)"
        GetRecordset(ctDSN_DEVFAC, szSQL, rs)
        Do While Not rs.EOF
            LV_LIGNES.Items.Add(rs.Fields("ref").Value)
            LV_LIGNES.Items(nb).SubItems.Add(nv(rs.Fields("lib").Value))
            If rs.Fields("qte").Value = 0 Then
                LV_LIGNES.Items(nb).SubItems.Add("")
            Else
                LV_LIGNES.Items(nb).SubItems.Add(FormatNumber(rs.Fields("qte").Value, 2))
            End If
            If rs.Fields("prixht").Value = 0 Then
                LV_LIGNES.Items(nb).SubItems.Add("")
            Else
                LV_LIGNES.Items(nb).SubItems.Add(rs.Fields("prixht").Value)
            End If
            If rs.Fields("mtht").Value = 0 Then
                LV_LIGNES.Items(nb).SubItems.Add("")
            Else
                LV_LIGNES.Items(nb).SubItems.Add(rs.Fields("mtht").Value)
            End If
            LV_LIGNES.Items(nb).SubItems.Add(rs.Fields("nolig").Value)
            LV_LIGNES.Items(nb).SubItems.Add(IfDate(rs.Fields("datemaj").Value) & " par " & rs.Fields("usermaj").Value)
            dTotalHT += rs.Fields("mtht").Value
            xLastNoLig = rs.Fields("nolig").Value
            rs.MoveNext()
            nb = nb + 1
        Loop
        rs.Close()

        TE_lg_TOTALHT.Text = FormatCurrency(dTotalHT)
        xTauxTVA = CDec(getTailCodeFromCombo(CB_TVA.SelectedItem).Replace("%", " "))
        TE_lg_TOTALTTC.Text = FormatCurrency(dTotalHT * (1 + xTauxTVA / 100))
        ' restaurer la position du curseur avant le init
        LV_LIGNES.Focus()
        setIndice(ix, LV_LIGNES)

    End Sub

    Private Sub LV_LIGNES_DoubleClick(sender As Object, e As System.EventArgs) Handles LV_LIGNES.DoubleClick

        If IsUserAuthorised(ctGestion) = False Then
            Exit Sub
        End If

        If LV_LIGNES.SelectedItems.Count > 0 Then
            xNolig = LV_LIGNES.SelectedItems(0).SubItems(5).Text
            Call LignetoScreen(xNolig)
            ' afficher les détails de la formule
            GB_DETAIL.Visible = True
            CB_REF.Focus()
        End If

    End Sub

    Private Sub LV_LIGNES_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles LV_LIGNES.KeyDown

        Select Case e.KeyCode
            ' touche Enter = DoubleClick
            Case Keys.Enter
                Call LV_LIGNES_DoubleClick(sender, e)

            Case Keys.Insert
                ' insère une ligne à la fin
                xNolig = 0
                ClearTextBoxes(GB_DETAIL)
                TE_QTE.Value = 1
                CB_REF.SelectedIndex = CB_REF.FindString("TX")
                GB_DETAIL.Visible = True
                CB_REF.Focus()

            Case Keys.Delete
                If LV_LIGNES.SelectedItems.Count > 0 Then
                    xNolig = LV_LIGNES.SelectedItems(0).SubItems(5).Text
                    ' Call LignetoScreen(xNolig)
                    deleteEnregistrement(xSousRub, LV_LIGNES.SelectedItems(0).SubItems(1).Text, pNoDossier, xNolig)
                    Call InitLignes(xNolig)
                    ' Cacher les détails
                    GB_DETAIL.Visible = False
                End If
        End Select

    End Sub

    Private Sub LignetoScreen(ByVal xNolig As Integer)

        szSQL = "CALL spGET_LIGNES('" & gSocieteCode & "','" & xSousRub & "'," & pNoDossier & "," & xNolig & ")"
        GetRecordset(ctDSN_DEVFAC, szSQL, rs)
        If rs.RecordCount < 1 Then
            rs.Close()
            Exit Sub
        End If

        CB_REF.SelectedIndex = CB_REF.FindString(nv(rs.Fields("ref").Value))
        TE_LIB.Text = nv(rs.Fields("lib").Value)
        TE_QTE.Value = rs.Fields("qte").Value
        TE_PRIXHT.Text = rs.Fields("prixht").Value
        rs.Close()
        GB_DETAIL.Visible = True

    End Sub

    Private Sub ScreenToLigne(ByVal nNolig As Integer)

        If nNolig = 0 Then   ' nouvelle ligne
            nNolig = xLastNoLig + 1
        End If

        szSQL = "CALL spGET_LIGNES('" & gSocieteCode & "','" & xSousRub & "'," & pNoDossier & "," & nNolig & ")"
        GetRecordset(ctDSN_DEVFAC, szSQL, rs)
        If rs.RecordCount < 1 Then
            ' créer une nouvelle ligne
            szSQL = "CALL spINS_LIGNE('" & gSocieteCode & "','" & xSousRub & "'," & pNoDossier & "," & nNolig & ")"
            ExecQuery(ctDSN_DEVFAC, szSQL)
        End If

        szSQL = "CALL spUPD_FACTURE_LIGNE('" & gSocieteCode & "'," & pNoDossier & "," & nNolig & ",'" & _
                CB_REF.SelectedItem & "','" & nq(TE_LIB.Text) & "'," & TE_QTE.Value & "," & TE_PRIXHT.Value & ",'" & gUserCode & "')"
        ExecQuery(ctDSN_DEVFAC, szSQL)

    End Sub

    Private Sub BO_IMPRIMER_Click(sender As System.Object, e As System.EventArgs) Handles BO_IMPRIMER.Click
        gNoDossier = pNoDossier
        frmEditions.pRubrique = xRubrique
        frmEditions.ShowDialog()
    End Sub

    Private Sub BO_SUPPRIMER_Click(sender As System.Object, e As System.EventArgs) Handles BO_SUPPRIMER.Click

        If IsUserAuthorised(ctCompta) = False Then
            Exit Sub
        End If

        ' utilisateur autorisé à supprimer ?
        If IsUserAuthorised(9) = False Then
            Exit Sub
        End If

        deleteEnregistrement(xRubrique, xRubrique & " de " & TE_NOM.Text, pNoDossier)
        ' ferme la fenetre
        Me.Close()

    End Sub

    Private Sub TE_ADR_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_ADR.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_COM_CL_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_DATEREG.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_COMMENT_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_COMMENT.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_DATE_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_DATE.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_EMAIL_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_EMAIL.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_LIBCOMPL_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_LIBCOMPL.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_NOPOL_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_NOPOL.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_NOSIN_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_NOSIN.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_QUALITE_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_QUALITE.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_REF_EXPERT_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_REF_EXPERT.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_VREF_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_VREF.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub CB_CABINETS_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles CB_CABINETS.KeyDown

        If e.KeyCode = Keys.Enter Then
            ' code cabinet a changé ?
            If CB_CABINETS.SelectedIndex <> xOldCabinet Then
                ' remplir le combo experts selon le cabinet lu
                InitComboExperts(CB_EXPERTS, getTailCodeFromCombo(CB_CABINETS.SelectedItem))
            End If
            Call Perform_tab_on_enter(e)
        End If

    End Sub

    Private Sub CB_EXPERTS_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles CB_EXPERTS.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub CB_QUALITE_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles CB_QUALITE.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub CB_TVA_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles CB_TVA.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub CB_TYPE_TRAV_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles CB_TYPE_TRAV.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_ADR_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_ADR.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_ADR2_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_ADR2.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_CODE_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_CODE.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_CP_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_CP.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_EMAIL_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_EMAIL.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_ETAGE_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_ETAGE.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_FAX_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_FAX.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_NOM_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_NOM.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_OBS_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_OBS.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_TEL1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_TEL1.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_TEL2_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_TEL2.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_TELP_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_TELP.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_C_VILLE_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_C_VILLE.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub ChkA_REVOIR_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles ChkA_REVOIR.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub TE_NOM_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_NOM.KeyDown

        If e.KeyCode = Keys.Return Then
            If TE_NOM.Text.Length = 0 Then
                MsgBox("Veuillez saisir un nom de client.", MsgBoxStyle.Critical)
                Exit Sub
            End If
            If TE_NOM.Text <> xOldNom Then
                ' le nom a changé, effectue la recherche
                frmClientSearch.pNOM_CLI = TE_NOM.Text
                frmClientSearch.pCD_CLI = 0
                frmClientSearch.ShowDialog()

                If frmClientSearch.pCD_CLI > 0 Then
                    TE_CD_CLI.Text = frmClientSearch.pCD_CLI
                    'Lire la Table  CLIENT par No du Client
                    szSQL = "CALL spGET_CLIENTS('" & gSocieteCode & "'," & TE_CD_CLI.Text & ")"
                    GetRecordset(ctDSN_DEVFAC, szSQL, rs)
                    If rs.RecordCount > 0 Then
                        TE_QUALITE.Text = nv(rs.Fields("qualite").Value)
                        TE_NOM.Text = rs.Fields("nom").Value
                        TE_ADR.Text = fAdresseClient(rs)
                        If TE_C_NOM.Text.Length = 0 Then
                            TE_C_NOM.Text = TE_NOM.Text
                            TE_C_ADR.Text = nv(rs.Fields("adresse").Value)
                            TE_C_ADR2.Text = nv(rs.Fields("adresse2").Value)
                            TE_C_CP.Text = nv(rs.Fields("cp").Value)
                            TE_C_VILLE.Text = nv(rs.Fields("ville").Value)
                        End If
                        TE_TYPECLI.Text = nv(rs.Fields("type").Value)
                        TE_GROUPE.Text = nv(rs.Fields("groupe").Value)
                        TE_NOCOMPTE.Text = nv(rs.Fields("nocompte").Value)
                        TE_NOTARIF.Text = nv(rs.Fields("notarif").Value)
                        TE_WEBSITE.Text = nv(rs.Fields("website").Value)
                        TE_COMMENT.Text = nv(rs.Fields("comment").Value)
                        If pNoDossier = 0 Then
                            ' si création, remplir le code cabinet selon le client
                            CB_CABINETS.SelectedIndex = getTailCodePosition(CB_CABINETS, rs.Fields("cabinet").Value)
                            xOldCabinet = rs.Fields("cabinet").Value
                            ' remplir le combo experts selon le cabinet lu
                            InitComboExperts(CB_EXPERTS, getTailCodeFromCombo(CB_CABINETS.SelectedItem))
                            CB_EXPERTS.SelectedIndex = getTailCodePosition(CB_EXPERTS, rs.Fields("expert").Value.ToString)
                        End If
                        CB_MODEREG.SelectedIndex = CB_MODEREG.FindString(rs.Fields("modereg").Value.ToString)
                        ' calculer la date d'échéance
                        If TE_TYPECLI.Text = "P" Then
                            TE_DATE_ECHEANCE.Value = DateAdd(DateInterval.Day, 8, TE_DATE.Value)
                        Else
                            TE_DATE_ECHEANCE.Value = DateAdd(DateInterval.Month, 1, TE_DATE.Value)
                        End If
                    End If
                    rs.Close()
                End If
            End If
            ' passe au champs suivant
            Call Perform_tab_on_enter(e)
        End If
    End Sub

    Private Sub BO_DEM_Click(sender As System.Object, e As System.EventArgs) Handles BO_DEM.Click
        ' affiche les détails du dossier sélectionné
        Call Show_Dossier("DD", BO_DEM.Text)
    End Sub

    Private Sub BO_ORDRE_Click(sender As System.Object, e As System.EventArgs) Handles BO_ORDRE.Click
        ' affiche les détails du dossier sélectionné
        Call Show_Dossier("OS", BO_ORDRE.Text)
    End Sub

    Private Sub BO_FACTURE_Click(sender As System.Object, e As System.EventArgs) Handles BO_DEVIS.Click
        ' affiche les détails du dossier sélectionné
        Call Show_Dossier("FA", BO_DEVIS.Text)
    End Sub

    Private Sub BO_MINO_MAJO_Click(sender As System.Object, e As System.EventArgs) Handles BO_MINO_MAJO.Click

        If IsUserAuthorised(ctGestion) = False Then
            Exit Sub
        End If
        If TE_COEFF.Value = 0 Then
            MsgBox("Veuillez saisir un pourcentage à appliquer.", MsgBoxStyle.Critical)
        End If
        ' Majorer/Minorer les prix ht
        szSQL = "CALL spUPD_LIGNES_MAJO('" & gSocieteCode & "'," & pNoDossier & "," & TE_COEFF.Value & ")"
        ExecQuery(ctDSN_DEVFAC, szSQL)

        Call DossierToScreen()

    End Sub

    Private Sub TE_NOTARIF_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_NOTARIF.KeyDown
        Call Perform_tab_on_enter(e)
    End Sub

    Private Sub CB_REF_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles CB_REF.KeyDown

        Select Case e.KeyCode
            Case Keys.Escape   ' quitter mode saisie
                GB_DETAIL.Visible = False

            Case Keys.Return   'Enregistrer directement
                Select Case CB_REF.SelectedItem
                    Case "TX"
                        TE_ART.Visible = False
                        TE_LIB.MaxLength = 45
                        Call Perform_tab_on_enter(e)
                    Case "TI"
                        TE_ART.Visible = False
                        TE_LIB.MaxLength = 31
                        Call Perform_tab_on_enter(e)
                    Case "CA"
                        TE_ART.Visible = False
                        TE_LIB.MaxLength = 40
                        Call Perform_tab_on_enter(e)
                    Case "AR"
                        TE_ART.Visible = True
                        TE_LIB.MaxLength = 45
                        Call Perform_tab_on_enter(e)
                    Case "ST", "TO"
                        TE_LIB.Text = ""
                        TE_QTE.Value = 0
                        TE_PRIXHT.Value = 0
                        ' enregistrer tout de suite
                        TE_PRIXHT_KeyDown(Nothing, New KeyEventArgs(Keys.Enter))
                    Case Else
                        MsgBox(CB_REF.SelectedItem & " : Type de ligne incorrect")
                End Select
        End Select

    End Sub

    Private Sub TE_LIB_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_LIB.KeyDown
        Dim iPoste As Integer
        Dim save_index As Integer

        Select Case e.KeyCode
            Case Keys.Escape   ' quitter mode saisie
                GB_DETAIL.Visible = False

            Case Keys.Return   'Enregistrer directement
                If CB_REF.SelectedItem = "CA" Then
                    TE_QTE.Value = Calculer(TE_LIB.Text)
                    ' enregistrer tout de suite
                    TE_PRIXHT_KeyDown(Nothing, New KeyEventArgs(Keys.Enter))
                Else
                    Perform_tab_on_enter(e)
                End If

            Case Keys.F5, Keys.F6  ' souligner par ----
                ' determiner la ligne précédente
                If xNolig = 0 Then  ' en création
                    save_index = 0
                    iPoste = LV_LIGNES.Items.Count - 1
                Else
                    save_index = LV_LIGNES.SelectedItems(0).Index
                    iPoste = save_index - 1
                End If
                LV_LIGNES.Select()
                LV_LIGNES.Items(iPoste).Selected = True
                TE_LIB.Text = Space(Len(LV_LIGNES.SelectedItems(0).SubItems(1).Text))
                If e.KeyCode = Keys.F5 Then
                    TE_LIB.Text = Replace(TE_LIB.Text, " ", "-")
                Else
                    TE_LIB.Text = Replace(TE_LIB.Text, " ", "=")
                End If
                TE_QTE.Value = 0
                TE_PRIXHT.Value = 0
                ' enregistrer tout de suite
                TE_PRIXHT_KeyDown(Nothing, New KeyEventArgs(Keys.Enter))
                Exit Sub

        End Select

    End Sub

    Private Sub TE_QTE_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_QTE.KeyDown
        Select Case e.KeyCode
            Case Keys.Escape   ' quitter mode saisie
                GB_DETAIL.Visible = False

            Case Keys.Return   'Enregistrer directement
                Perform_tab_on_enter(e)

            Case Keys.F7 'Cumuler les calculs
                TE_QTE.Value = Cumuler()
                TE_LIB.Text = ""
                TE_PRIXHT.Focus()

        End Select
    End Sub

    Private Sub TE_PRIXHT_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_PRIXHT.KeyDown

        If e.KeyCode = Keys.Return Then
            Call ScreenToLigne(xNolig)
            GB_DETAIL.Visible = False
            If xNolig = 0 Then
                InitLignes(LV_LIGNES.Items.Count)
            Else
                InitLignes(xNolig)
            End If
            LV_LIGNES.Focus()
        End If

    End Sub

    Private Sub BO_EMAIL_Click(sender As System.Object, e As System.EventArgs) Handles BO_EMAIL.Click

        Exit Sub
        ' Calculer les totaux de la facture
        szSQL = "CALL spUPD_FACTURE_TOTAUX('" & gSocieteCode & "'," & pNoDossier & ")"
        GetRecordset(ctDSN_DEVFAC, szSQL, rs)
        If rs.RecordCount > 0 Then
            xNbSousTotaux = rs.Fields("l_groupe").Value
        Else
            xNbSousTotaux = 0
        End If
        rs.Close()

        ' Sélection de l'état selon avec/sans sous-totaux
        If xNbSousTotaux = 0 Then
            frmEmail.pReport = gSocieteCode & "-" & xRubrique & "_E.RPT"
        Else
            frmEmail.pReport = gSocieteCode & "-" & xRubrique & "ST_E.RPT"
        End If
        ' afficher le form EMAIL
        frmEmail.pRubrique = xRubrique
        frmEmail.pNoDossier = pNoDossier
        frmEmail.Show()

        '  FrmEditer.Visible = False
        LV_LIGNES.Focus()
    End Sub

    Private Sub BO_EDITER_FACTURE_Click(sender As System.Object, e As System.EventArgs) Handles BO_EDITER_FACTURE.Click

        'Dim szformula As String

        ' Calculer les totaux du devis
        szSQL = "CALL spUPD_FACTURE_TOTAUX('" & gSocieteCode & "'," & gNoDossier & ")"
        GetRecordset(ctDSN_DEVFAC, szSQL, rs)
        If rs.RecordCount > 0 Then
            xNbSousTotaux = rs.Fields("l_groupe").Value
        Else
            xNbSousTotaux = 0
        End If
        rs.Close()

        TE_NbEx.Value = 1

        Select Case gSocieteCode
            Case "PO"
                szSQL = "\PO-" & xRubrique
            Case "PL"
                szSQL = "\PL-" & xRubrique
            Case Else
                szSQL = "\" & xRubrique
        End Select

        If chk_Chantier.Checked = True Then
            ' Sélection de l'état selon avec/sans sous-totaux
            If xNbSousTotaux = 0 Then
                szSQL = szSQL & "Chan.RPT"
            Else
                szSQL = szSQL & "ChanST.rpt"
            End If
        Else
            ' Sélection de l'état selon avec/sans sous-totaux
            If xNbSousTotaux = 0 Then
                szSQL = szSQL & ".RPT"
            Else
                szSQL = szSQL & "ST.rpt"
            End If
        End If

        ' édition de l'étatRPT
        gNoDossier = pNoDossier
        frmViewReport.pNomEtat = szSQL
        frmViewReport.pParamRPT = ""
        frmViewReport.ShowDialog()

        'szformula = "{Facture.societe}='" & gSocieteCode & "' AND {facture.no_id}=" & gNoDossier
        'PrintToPrinter(szSQL, szformula, "ee")

    End Sub

    Private Sub BO_ADD_LIGNE_Click(sender As System.Object, e As System.EventArgs) Handles BO_ADD_LIGNE.Click
        Call Lignes_Selection("INS")
    End Sub

    Private Sub BO_COPY_Click(sender As System.Object, e As System.EventArgs) Handles BO_COPY.Click
        Call Lignes_Selection("DUP")
    End Sub

    Private Sub BO_DELETE_LIGNE_Click(sender As System.Object, e As System.EventArgs) Handles BO_DELETE_LIGNE.Click
        Call Lignes_Selection("DEL")
    End Sub

    Private Sub BO_ANNULER_Click(sender As System.Object, e As System.EventArgs) Handles BO_ANNULER.Click
        GB_INSERER.Visible = False
        LV_LIGNES.Focus()
    End Sub

    Private Sub BO_INSERER_Click(sender As System.Object, e As System.EventArgs) Handles BO_INSERER.Click

        Select Case BO_INSERER.Text
            Case "Insérer"
                ' insérer des lignes blanches à partir de la ligne courante
                szSQL = "CALL spINS_LIGNES_TX_DEVIS('" & xRubrique & "','" & gSocieteCode & "'," & pNoDossier & "," & xNolig & _
                                                  "," & EL_NOMBRE.Value & ",'" & gUserCode & "')"
                ExecQuery(ctDSN_DEVFAC, szSQL)
                MsgBox(EL_NOMBRE.Value & " lignes ont été insérées")

            Case "Duppliquer"
                If EL_NOMBRE.Value <= xNolig Then
                    MsgBox("Numéros de lignes départ ou arrivée incohérents!", vbInformation)
                    Exit Sub
                End If
                ' duppliquer des lignes à partir de la ligne courante
                szSQL = "CALL spDUP_LIGNES_DEVIS('" & xRubrique & "','" & gSocieteCode & "'," & pNoDossier & "," & xNolig & "," & EL_NOMBRE.Value & "," & EL_VERS.Value & ")"
                ExecQuery(ctDSN_DEVFAC, szSQL)
                MsgBox(LV_LIGNES.SelectedItems.Count & " lignes ont été duppliquées")

            Case "Supprimer"
                If EL_NOMBRE.Value < xNolig Then
                    MsgBox("Numéros de lignes départ ou arrivée incohérents!", vbInformation)
                    Exit Sub
                End If
                ' Supprimer les lignes à partir de la ligne courante
                szSQL = "CALL spDEL_LIGNES_DEVIS('" & xRubrique & "','" & gSocieteCode & "'," & pNoDossier & "," & xNolig & "," & EL_NOMBRE.Value & ")"
                ExecQuery(ctDSN_DEVFAC, szSQL)
                MsgBox(EL_NOMBRE.Value - xNolig + 1 & " lignes ont été supprimées")

        End Select
        GB_INSERER.Visible = False
        Call InitLignes(LV_LIGNES.SelectedIndices.Item(0))
        'LV_LIGNES.Focus()

    End Sub

    Private Sub Lignes_Selection(action As String)

        ' mémoriser numéro de la ligne en cours
        If LV_LIGNES.SelectedItems.Count < 1 Then
            Exit Sub
        End If
        xNolig = LV_LIGNES.SelectedItems(0).SubItems(5).Text
        EL_LIB.Text = LV_LIGNES.SelectedItems(0).SubItems(0).Text & " " & LV_LIGNES.SelectedItems(0).SubItems(1).Text

        Select Case action
            Case "INS"
                GB_INSERER.Text = "INSERER à partir de la ligne " & xNolig
                EL_ACTION.Text = "Nombre de lignes"
                el_TO.Visible = False
                EL_VERS.Visible = False
                BO_INSERER.Text = "Insérer"
                EL_NOMBRE.Value = 3

            Case "DUP"
                GB_INSERER.Text = "DUPPLIQUER à partir de la ligne " & xNolig
                EL_ACTION.Text = "jusqu'à la ligne"
                EL_TO.Visible = True
                EL_VERS.Visible = True
                BO_INSERER.Text = "Duppliquer"
                EL_NOMBRE.Value = LV_LIGNES.SelectedItems(LV_LIGNES.SelectedItems.Count - 1).SubItems(5).Text

            Case "DEL"
                GB_INSERER.Text = "Supprimer à partir de la ligne " & xNolig
                EL_ACTION.Text = "jusqu'à la ligne"
                EL_TO.Visible = False
                EL_VERS.Visible = False
                BO_INSERER.Text = "Supprimer"
                EL_NOMBRE.Value = LV_LIGNES.SelectedItems(LV_LIGNES.SelectedItems.Count - 1).SubItems(5).Text

        End Select
        GB_INSERER.Location = New Point(295, 141)
        GB_INSERER.Visible = True
        EL_NOMBRE.Focus()

    End Sub

    Private Sub BO_NEW_NUMERO_Click(sender As System.Object, e As System.EventArgs) Handles BO_NEW_NUMERO.Click

        If IsUserAuthorised(ctGestion) = False Then
            Exit Sub
        End If
        ' maj numéro FACTURE
        szSQL = "CALL spUPD_FACTURE_NOID('" & gSocieteCode & "'," & pNoDossier & "," & BO_DEVIS.Text & "," & _
                 BO_ORDRE.Text & "," & TE_NEW_NO.Value & ")"

        If ExecQuery(ctDSN_DEVFAC, szSQL) = True Then
            MsgBox(xRubrique & " modifiée")
            Me.Close()
        End If

    End Sub

    Private Sub TE_ART_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_ART.KeyDown
        Dim rsArt As ADODB.Recordset = Nothing

        If e.KeyCode = Keys.Escape Then  'sortir mode création ligne
            GB_DETAIL.Visible = False
            Exit Sub
        End If
        If e.KeyCode = Keys.Return Then  'Traiter ENTREE
            szSQL = "CALL spGET_ARTICLES('" & gSocieteCode & "','" & TE_ART.Text & "')"
            GetRecordset(ctDSN_DEVFAC, szSQL, rsArt)
            If rsArt.RecordCount < 1 Then
                rs.Close()
                Exit Sub
            End If
            TE_LIB.Text = rsArt.Fields("libart").Value
            CB_REF.SelectedIndex = CB_REF.FindString("TX")
            TE_QTE.Value = 1
            Call ScreenToLigne(0)
            ' créer libellé complémentaire
            If nv(rsArt.Fields("libcompl1").Value) <> "" Then
                TE_LIB.Text = rsArt.Fields("libcompl1").Value
                xNolig = xNolig + 1
                Call ScreenToLigne(xNolig)
            End If
            If nv(rsArt.Fields("libcompl2").Value) <> "" Then
                TE_LIB.Text = rsArt.Fields("libcompl2").Value
                xNolig = xNolig + 1
                Call ScreenToLigne(xNolig)
            End If
            If nv(rsArt.Fields("libcompl3").Value) <> "" Then
                TE_LIB.Text = rsArt.Fields("libcompl3").Value
                xNolig = xNolig + 1
                Call ScreenToLigne(xNolig)
            End If
            If nv(rsArt.Fields("libcompl4").Value) <> "" Then
                TE_LIB.Text = rsArt.Fields("libcompl4").Value
                xNolig = xNolig + 1
                Call ScreenToLigne(xNolig)
            End If

            Select Case TE_NOTARIF.Value   ' selon le tarif facture
                Case 1
                    TE_PRIXHT.Value = rsArt.Fields("prixht1").Value
                Case 2
                    TE_PRIXHT.Value = rsArt.Fields("prixht2").Value
                Case 3
                    TE_PRIXHT.Value = rsArt.Fields("prixht3").Value
                Case 4
                    TE_PRIXHT.Value = rsArt.Fields("prixht4").Value
                Case 5
                    TE_PRIXHT.Value = rsArt.Fields("prixht5").Value
                Case 6
                    TE_PRIXHT.Value = rsArt.Fields("prixht6").Value
                Case 7
                    TE_PRIXHT.Value = rsArt.Fields("prixht7").Value
                Case 8
                    TE_PRIXHT.Value = rsArt.Fields("prixht8").Value
                Case 9
                    TE_PRIXHT.Value = rsArt.Fields("prixht9").Value
                Case 10
                    TE_PRIXHT.Value = rsArt.Fields("prixht10").Value
            End Select
            If TE_PRIXHT.Value = 0 Then
                TE_QTE.Value = 1
                TE_PRIXHT.Focus()
            Else
                TE_QTE.Value = 0
                TE_QTE.Focus()
            End If
            rs.Close()
        End If

    End Sub

    Private Sub BO_CABINET_Click(sender As System.Object, e As System.EventArgs) Handles BO_CABINET.Click
        ' afficher le Cabinet 
        frmCabinetMAJ.pCode_cab = getTailCodeFromCombo(CB_CABINETS.SelectedItem)
        frmCabinetMAJ.ShowDialog()
    End Sub

    Private Sub BO_COMPTE_CLIENT_Click(sender As System.Object, e As System.EventArgs) Handles BO_COMPTE_CLIENT.Click
        ' afficher les comptes 
        frmClientCPT.pCd_cli = TE_CD_CLI.Text
        frmClientCPT.pNom_cli = TE_NOM.Text
        frmClientCPT.ShowDialog()
    End Sub

    Private Function Cumuler() As Single
        ' Cumuler les Qte des Calculs
        Dim iPoste As Integer
        Dim save_index As Integer
        Dim szRef As String

        Cumuler = 0
        ' determiner la ligne précédente
        If xNolig = 0 Then  ' en création
            save_index = 0
            iPoste = LV_LIGNES.Items.Count - 1
        Else
            save_index = LV_LIGNES.SelectedItems(0).Index
            iPoste = save_index - 1
        End If
        LV_LIGNES.Select()

        ' balayer en remontant la LD_LIGNES
        Do While iPoste >= 0
            LV_LIGNES.Items(iPoste).Selected = True
            szRef = LV_LIGNES.SelectedItems(0).SubItems(0).Text
            If szRef = "CA" Then
                ' col Quantité
                If IsNumeric(LV_LIGNES.SelectedItems(0).SubItems(2).Text) Then
                    Cumuler = Cumuler + CDec(LV_LIGNES.SelectedItems(0).SubItems(2).Text)
                End If
            Else
                ' col Prix
                If IsNumeric(LV_LIGNES.SelectedItems(0).SubItems(3).Text) Then
                    TE_PRIXHT.Value = CDec(LV_LIGNES.SelectedItems(0).SubItems(3).Text)
                    Exit Do
                Else
                    TE_PRIXHT.Value = 0
                End If
            End If
            iPoste = iPoste - 1
        Loop

    End Function


End Class
